﻿Imports System
Imports System.Configuration
Imports System.Web
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Public Class BannerHttpHandler
    Implements IHttpHandler

    'ProcessRequest - enable processing of HTTPWebRequest by a custome HTTPHandler that Implennts IHTTP Handler interface
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        ' declare imageID as Integer
        Dim imageID As Int32
        'if the imageID have things then convert to int 
        'if not throw a exception 
        If Not context.Request.QueryString("id") Is Nothing Then
            imageID = Convert.ToInt32(context.Request.QueryString("id"))
        Else
            Throw New ArgumentException("No parameter specified")
        End If
        Try
            context.Response.ContentType = "image/jpeg"
            Dim strm As Stream = ShowImage(imageID)
            Dim buffer As Byte() = New Byte(4095) {}
            Dim byteSeq As Integer = strm.Read(buffer, 0, 4096)

            Do While byteSeq > 0
                context.Response.OutputStream.Write(buffer, 0, byteSeq)
                byteSeq = strm.Read(buffer, 0, 4096)
            Loop
            'context.Response.BinaryWrite(buffer);
        Catch ex As Exception
        End Try

    End Sub

    Public Function ShowImage(ByVal imageID As Integer) As Stream
        Dim conn As String = ConfigurationManager.ConnectionStrings("goodAnotDBConnectionString").ConnectionString
        Dim connection As SqlConnection = New SqlConnection(conn)
        'getting the image from imageID
        Dim sql As String = "SELECT image from adv_image where adv_image_ID = @imageID"
        Dim cmd As SqlCommand = New SqlCommand(sql, connection)
        cmd.CommandType = CommandType.Text
        cmd.Parameters.AddWithValue("@imageID", imageID)
        connection.Open()
        Dim img As Object = cmd.ExecuteScalar()
        Try
            Return New MemoryStream(CType(img, Byte()))
        Catch
            Return Nothing
        Finally
            connection.Close()
        End Try
    End Function
    ' Get a value indicating request can use the IHTTPHandler instance
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property


End Class